<?php

namespace app\mobile\controller;

use app\common\model\CardBirthdayCareLog;
use app\common\model\CardBizPut;
use app\common\model\CardClickReplyPut;
use app\common\model\CardClickReplyPutlog;
use app\common\model\CardCzLog;
use app\common\model\CardFollowcard;
use app\common\model\CardFollowcardlog;
use app\common\model\CardFreecard;
use app\common\model\CardFreecardlog;
use app\common\model\CardGeneral;
use app\common\model\CardGivecardLog;
use app\common\model\CardGivePutCard;
use app\common\model\CardMember;
use app\common\model\CardPaycardlog;
use app\common\model\CardRankUserLog;
use app\common\model\CardShareLog;
use app\common\model\CardUserGet;
use app\common\model\Merchant;
use app\common\model\Momerchant;
use app\common\model\PaymentCardPutLog;
use app\common\model\WxOpen;
use think\Controller;
use think\Debug;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;
use Wnkj\WnObj;

class Cardgettest extends Mobilebase
{


    public function getcards1(){
        return $this->fetch();
    }

    public function getcards2(){
        return $this->fetch();
    }

    public function getcards3(){
        return $this->fetch();
    }

    public function getcards4(){
        return $this->fetch();
    }

    public function logtest()
    {

        try {
            $param = request()->post();
            if (isset($param['info']['cardList'])) {
                $cardlist = $param['info']['cardList'];
                $CardUserGet = new CardUserGet();
                foreach ($cardlist as $k => $v) {
                    $cardv = json_decode($v['cardExt'], true);
                    if (strpos($cardv['outer_str'], 'RecId_')) {
                        $outerstr = explode('_', $cardv['outer_str']);
                        $givelogid = end($outerstr);
                        if ($givelogid) {
                            $getsum = $CardUserGet->where(['outerstr' => $cardv['outer_str']])->count('id');
                            $CardGivecardLog = new CardGivecardLog();
                            $CardCzLog = new CardCzLog();
                            $give_rec_id = $CardGivecardLog->where(['id' => $givelogid, 'zs_card_id' => $v['cardId']])->value('give_rec_id');
                            $CardCzLog->where(['id' => $give_rec_id])->field('id,zs_card_statu')->find();
                            $CardCzLog->save(['zs_card_statu' => 1], ['id' => $give_rec_id]);
                            $CardGivecardLog->where(['id' => $givelogid, 'zs_card_id' => $v['cardId']])->setInc('get_sume', 1);
                            $CardGivecardLog->save(['get_sume' => $getsum], ['id' => $givelogid, 'zs_card_id' => $v['cardId']]);
                        }
                    }
                }
            }

        } catch (\Exception $e) {
            $data2 = json_encode(array('code' => '9099', 'message' => $e->getMessage()));

        }

    }

    //充值发送礼品领卡
    /*
     * $card_id
     */
    public function getcardsbirthdaycare()
    {
//        try {
            $arr = request()->param();
            $this->_init();
            $CardBirthdayCareLog = new CardBirthdayCareLog();
            $Merchant = new Merchant();
            $Momerchant = new Momerchant();
            $top_mid = $Merchant->where('id', $arr['mid'])->value('top_mid');
            $sinfo = $Momerchant->where('id', $top_mid)->value('wx_open_id');
            $WxOpen = new WxOpen();
            $sappid = $WxOpen->where('id', $sinfo)->value('authorizer_appid');
            $logopenid = $CardBirthdayCareLog->where(['id' => $arr['rec_id'], 'put_type' => 'birthdaycare','statu'=>'N'])->value('openid');
            $openid = Session::get($sappid . '_openid');
            //判断领卡人是否正确]
            if ($logopenid == $openid) {
                $map['openid'] = Session::get($sappid . '_openid');
                $midarr = $Merchant->where('top_mid', $top_mid)->field('id')->select();
                $smid = [];
                foreach ($midarr as $key => $value) {
                    $smid[] = $value['id'];
                }
                $mid = implode(",", $smid);
                $map['mid'] = ['in', $mid];
                $map['have'] = 1;
                $map['card_type'] = 'MEMBER_CARD';
                $CardUserGet = new CardUserGet();
                $user = $CardUserGet->where($map)->find();
                if ($user) {
                    $CardGivecardLog = new CardGivecardLog();
                    $maps['mid'] = $arr['mid'];
                    $maps['give_rec_id'] = $arr['rec_id'];
                    $maps['put_type'] = 'birthdaycare';
                    $cardlist = $CardGivecardLog->where($maps)->select();
                    $card = [];
                    foreach ($cardlist as $k => $v) {
                        $outer_str = 'giveRecId_' . $v['id'];
                        $isgetput = $this->isgetputsume($v['zs_card_id'], $outer_str, $openid, $v['put_sume']);
                        if ($v['put_sume'] > $v['get_sume'] && $isgetput == 0 && filtercarduselimitdedu($v['zs_card_id'],$openid) &&  getcardgetsume($v['zs_card_id']) > getcardgetuser($v['zs_card_id'], $openid)) {
                            for ($x = 0; $x < $v['put_sume']; $x++) {
//                        var_dump(json_encode($v));
                                $options = $this->options($v['zs_card_id']);
                                $arrs['card_id'] = $v['zs_card_id'];
                                $arrs['openid'] = $openid;
                                $arrs['outer_str'] = 'giveRecId_' . $v['id'];
                                $card[] = $this->putlist($arrs);
                            }
                        }
                    }
                    $this->assign('cardlist', $cardlist);
                    if (isset($options)) {
                        $weObj = new Wxobjopen($options);
                        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                        $jssdk = $weObj->getJsSign($url);
                        $this->assign('card', json_encode($card));
                        $this->assign('jssdk', $jssdk);
                        return $this->fetch('getcardspay');
                    } else {
                        return $this->fetch('getoff');
                    }

                }
            } else {
                echo "<div style='margin-top:30%;font-size: 70px;text-align: center '>您没有可领取卡券</div>";
            }
    }

    //充值发送礼品领卡
    /*
     * $card_id
     */
    public function getcards()
    {
        try {
            $arr = request()->param();
            $this->_init();
            $CardCzLog = new CardCzLog();
            $Merchant = new Merchant();
            $top_mid = $Merchant->where('id', $arr['mid'])->value('top_mid');
            $sinfo = $Merchant->where('id', $arr['mid'])->value('wx_open_id');
            $WxOpen = new WxOpen();
            $sappid = $WxOpen->where('id', $sinfo)->value('authorizer_appid');
            $logopenid = $CardCzLog->where(['id' => $arr['rec_id']])->value('openid');
            $openid = Session::get($sappid . '_openid');
            //判断领卡人是否正确]
            if ($logopenid == $openid) {
                $map['openid'] = Session::get($sappid . '_openid');
                $midarr = $Merchant->where('top_mid', $top_mid)->field('id')->select();
                $smid = [];
                foreach ($midarr as $key => $value) {
                    $smid[] = $value['id'];
                }
                $mid = implode(",", $smid);
                $map['mid'] = ['in', $mid];
                $map['have'] = 1;
                $map['card_type'] = 'MEMBER_CARD';
                $CardUserGet = new CardUserGet();
                $user = $CardUserGet->where($map)->find();
                if ($user) {
                    $CardGivecardLog = new CardGivecardLog();
                    $cardlist = $CardGivecardLog->where(['mid' => $arr['mid'], 'give_rec_id' => $arr['rec_id']])->select();
//                $usercardlist = [];
                    foreach ($cardlist as $k => $v) {
                        $outer_str = 'giveRecId_' . $v['id'];
                        $isgetput = $this->isgetputsume($v['zs_card_id'], $outer_str, $openid, $v['put_sume']);
                        if ($v['put_sume'] > $v['get_sume'] && $isgetput == 0) {
                            $options = $this->options($v['zs_card_id']);
                            $usercardlist[$k]['card_id'] = $v['zs_card_id'];
                            $usercardlist[$k]['get_num'] = $v['put_sume'] - $v['get_sume'];
                        }
                    }
                    $this->assign('cardlist', $cardlist);
                    if (isset($usercardlist)) {
                        $this->assign('arr', $arr);
                        $this->assign('usercard', $usercardlist);
                        return $this->fetch();
                    } else {
                        return $this->fetch('getoff');
                    }
                }
            } else {

                echo "<div style='margin-top:30%;font-size: 70px;text-align: center '>您没有可领取卡券</div>";
            }
        } catch (\Exception $e) {

            echo "系统繁忙，请稍后再试！！！";
        }

    }

    public function getcardslistnu()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            $CardCzLog = new CardCzLog();
            $Merchant = new Merchant();
            $top_mid = $Merchant->where('id', $arr['mid'])->value('top_mid');
            $sinfo = $Merchant->where('id', $arr['mid'])->value('wx_open_id');
            $WxOpen = new WxOpen();
            $sappid = $WxOpen->where('id', $sinfo)->value('authorizer_appid');
            $logopenid = $CardCzLog->where(['id' => $arr['rec_id']])->value('openid');
            $openid = Session::get($sappid . '_openid');
            //判断领卡人是否正确]
            if ($logopenid == $openid) {
                $map['openid'] = Session::get($sappid . '_openid');
                $midarr = $Merchant->where('top_mid', $top_mid)->field('id')->select();
                $smid = [];
                foreach ($midarr as $key => $value) {
                    $smid[] = $value['id'];
                }
                $mid = implode(",", $smid);
                $map['mid'] = ['in', $mid];
                $map['have'] = 1;
                $map['card_type'] = 'MEMBER_CARD';
                $CardUserGet = new CardUserGet();
                $user = $CardUserGet->where($map)->find();
                if ($user) {
                    $CardGivecardLog = new CardGivecardLog();
                    $cardlist = $CardGivecardLog->where(['mid' => $arr['mid'], 'give_rec_id' => $arr['rec_id']])->select();
                    $card = [];
                    foreach ($cardlist as $k => $v) {
                        $outer_str = 'giveRecId_' . $v['id'];
                        $isgetput = $this->isgetputsume($v['zs_card_id'], $outer_str, $openid, $v['put_sume']);
                        if ($v['put_sume'] > $v['get_sume'] && $isgetput == 0) {
                            for ($x = 0; $x < $v['put_sume']; $x++) {
                                $options = $this->options($v['zs_card_id']);
                                $arrs['card_id'] = $v['zs_card_id'];
                                $arrs['openid'] = $openid;
                                $arrs['outer_str'] = 'giveRecId_' . $v['id'];
                                $card[] = $this->putlist($arrs);
                            }
                        }
                    }
                    if (isset($options)) {
                        $weObj = new Wxobjopen($options);
                        $url = $arr['url'];
                        $jssdk = $weObj->getJsSign($url);
                        $data['code'] = 0;
                        $data['message'] = 'success';
                        $data['data']['jssdk'] = $jssdk;
                        $data['data']['card'] = $card;
                    } else {
                        $data['code'] = 9001;
                        $data['message'] = '您已领取完成';
                    }
                } else {
                    $data['code'] = 9002;
                    $data['message'] = '领卡信息有误';
                }
            } else {
                $data['code'] = 9003;
                $data['message'] = '领卡信息有误';
            }
            return json($data);
        }
    }

    //判断领取数量是否达到发放数量
    private function isgetputsume($card_id, $outerstr, $openid, $put_sume)
    {
        try {
            $CardUserGet = new CardUserGet();
            $map['card_id'] = $card_id;
            $map['outerstr'] = $outerstr;
            $map['openid'] = $openid;
            $get_sume = $CardUserGet->where($map)->count('id');
            if ($put_sume < $get_sume || $put_sume == $get_sume) {
                return 1;
            } else {
                return 0;
            }
        } catch (\Exception $e) {
            return 0;
        }
    }


    //充值发送礼品领卡
    /*
     * $card_id
     */
    public function getfirecards()
    {
        try {
            $arr = request()->param();
            $this->_init();
            $CardGivePutCard = new CardGivePutCard();
            $Merchant = new Merchant();
            $Momerchant = new Momerchant();
            $CardMermber = new CardMember();
            $top_mid = $CardMermber->where('card_id', $arr['card_id'])->value('top_mid');
            $sinfo = $Momerchant->where('id', $top_mid)->value('wx_open_id');
            $WxOpen = new WxOpen();
            $sappid = $WxOpen->where('id', $sinfo)->value('authorizer_appid');
            $logopenid = $CardGivePutCard->where(['id' => $arr['rec_id'], 'give_type' => 'fire_card'])->value('openid');
            $openid = Session::get($sappid . '_openid');

            //判断领卡人是否正确]
            if ($logopenid == $openid) {
                $map['openid'] = Session::get($sappid . '_openid');
                $midarr = $Merchant->where('top_mid', $top_mid)->field('id')->select();
                $smid = [];
                foreach ($midarr as $key => $value) {
                    $smid[] = $value['id'];
                }
                $mid = implode(",", $smid);
                $map['mid'] = ['in', $mid];
                $map['have'] = 1;
                $map['card_type'] = 'MEMBER_CARD';
                $CardUserGet = new CardUserGet();
                $user = $CardUserGet->where($map)->find();
                if ($user) {
                    $CardGivecardLog = new CardGivecardLog();
                    $cardlist = $CardGivecardLog->where(['top_mid' => $top_mid, 'give_rec_id' => $arr['rec_id'], 'put_type' => 'fire_card'])->select();
                    $card = [];
                    foreach ($cardlist as $k => $v) {
                        $outer_str = 'giveRecId_' . $v['id'];
                        $isgetput = $this->isgetputsume($v['zs_card_id'], $outer_str, $openid, $v['put_sume']);
                        if ($v['put_sume'] > $v['get_sume'] && $isgetput == 0) {
                            for ($x = 0; $x < $v['put_sume']; $x++) {
//                        var_dump(json_encode($v));
                                $options = $this->options($v['zs_card_id']);
                                $arrs['card_id'] = $v['zs_card_id'];
                                $arrs['openid'] = $openid;
                                $arrs['outer_str'] = 'giveRecId_' . $v['id'];
                                $card[] = $this->putlist($arrs);
                            }
                        }
                    }
                    $this->assign('cardlist', $cardlist);
                    if (isset($options)) {
                        $weObj = new Wxobjopen($options);
                        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                        $jssdk = $weObj->getJsSign($url);
                        $this->assign('card', json_encode($card));
                        $this->assign('jssdk', $jssdk);
                        return $this->fetch('getcardspay');
                    } else {
                        return $this->fetch('getoff');
                    }

                }
            } else {
                var_dump('您没有可领取卡券');
//            return $this->fetch('off');
            }
        } catch (\Exception $e) {

            echo "系统繁忙，请稍后再试！！！";
        }
    }

    public function getfirecard(Request $request)
    {
        try {
            $this->_init();
            $param = $request->param();
            $Momerchant = new Momerchant();
            $sinfo = $Momerchant->where('id', $param['momach_id'])->value('wx_open_id');
            $WxOpen = new WxOpen();
            $sappid = $WxOpen->where('id', $sinfo)->value('authorizer_appid');
            $openid = Session::get($sappid . '_openid');
            $CardGivecardLog = new CardGivecardLog();
            $map['top_mid'] = $param['momach_id'];
            $map['card_id'] = $param['card_id'];
            $map['openid'] = $openid;
            $map['put_type'] = 'fire_card';
            $cardlist = $CardGivecardLog->where($map)->field('id,zs_card_id,put_sume,get_sume')->select();
            $cardlist = collection($cardlist)->toArray();
            $card = [];
            $cards['cardlist'] = $cardlist;
            $cards['openid'] = $openid;
            $WnObj = new WnObj($cards);
            $arrs = $WnObj->isgetputsume_biz();
            $options = $this->options($param['card_id']);
            $this->assign('cardlist', $cardlist);
            if (!empty($arrs)) {
                foreach ($arrs as $k => $v) {
                    for ($x = 0; $x < $v['put_sume']; $x++) {
                        $card[] = $this->putlist($v);
                    }
                }
                $weObj = new Wxobjopen($options);
                $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                $jssdk = $weObj->getJsSign($url);
                $this->assign('card', json_encode($card));
                $this->assign('jssdk', $jssdk);

                return $this->fetch('getcardspay');
            } else {
                return $this->fetch('getoff');
            }
        } catch (\Exception $e) {
            echo '系统繁忙，请稍后再试！！！';
            echo $e->getMessage();
        }
    }

    //付费购券列表
    public function getpaycards()
    {
        try {
            $arr = request()->param();
            $this->_init();
            $CardPaycardlog = new CardPaycardlog();
            $Merchant = new Merchant();
            $Momerchant = new Momerchant();
            $CardMermber = new CardMember();
            //没有card_id则从rec_id中查询
            if (isset($arr['card_id'])) {
                $top_mid = $CardMermber->where('card_id', $arr['card_id'])->value('top_mid');
            } else {
                $mid = $CardPaycardlog->where(['id' => $arr['rec_id']])->value('mid');
                $top_mid = $Merchant->where(['id' => $mid])->value('top_mid');
            }

            $sinfo = $Momerchant->where('id', $top_mid)->value('wx_open_id');
            $WxOpen = new WxOpen();
            $sappid = $WxOpen->where('id', $sinfo)->value('authorizer_appid');
            $logopenid = $CardPaycardlog->where(['id' => $arr['rec_id']])->value('openid');
            $openid = Session::get($sappid . '_openid');

            //判断领卡人是否正确]
            if ($logopenid == $openid) {
//            $map['openid'] = Session::get($sappid.'_openid');
//            $midarr = $Merchant->where('top_mid', $top_mid)->field('id')->select();
//            foreach ($midarr as $key => $value) {
//                $smid[] = $value['id'];
//            }
//            $mid = implode(",", $smid);
//            $map['mid'] = ['in', $mid];
//            $map['have'] = 1;
//            $map['card_type'] = 'MEMBER_CARD';
//            $CardUserGet = new CardUserGet();
//            $user = $CardUserGet->where($map)->find();
//            if ($user) {
                $CardGivecardLog = new CardGivecardLog();
                $cardlist = $CardGivecardLog->where(['top_mid' => $top_mid, 'give_rec_id' => $arr['rec_id'], 'put_type' => 'paycard'])->select();
                $card = [];
                foreach ($cardlist as $k => $v) {
                    $outer_str = 'giveRecId_' . $v['id'];
                    $isgetput = $this->isgetputsume($v['zs_card_id'], $outer_str, $openid, $v['put_sume']);
                    if ($v['put_sume'] > $v['get_sume'] && $isgetput == 0) {

                        for ($x = 0; $x < $v['put_sume']; $x++) {
//                        var_dump(json_encode($v));
                            $options = $this->options($v['zs_card_id']);
                            $arrs['card_id'] = $v['zs_card_id'];
                            $arrs['openid'] = $openid;
                            $arrs['outer_str'] = 'giveRecId_' . $v['id'];
                            $card[] = $this->putlist($arrs);
                        }
                    }
                }
                $this->assign('cardlist', $cardlist);
                if (isset($options)) {
                    $weObj = new Wxobjopen($options);
                    $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                    $jssdk = $weObj->getJsSign($url);
                    $this->assign('card', json_encode($card));
                    $this->assign('jssdk', $jssdk);
                    return $this->fetch('getcardspay');
                } else {
                    return $this->fetch('getoff');
                }

//                $this->assign('cardlist', $cardlist);
//                return $this->fetch('getlist');
//            }
            } else {

                var_dump('您没有可领取卡券');
//            return $this->fetch('off');
            }
        } catch (\Exception $e) {

            echo "系统繁忙，请稍后再试！！！";
        }
    }

    //关注送券
    public function getfollowcards()
    {
        try {
            $arr = request()->param();
            $this->_init();
            $CardFollowcardlog = new CardFollowcardlog();
            $Momerchant = new Momerchant();
            $CardMermber = new CardMember();
            //没有card_id则从rec_id中查询
            if (isset($arr['card_id'])) {
                $top_mid = $CardMermber->where('card_id', $arr['card_id'])->value('top_mid');
            } else {
                $top_mid = $CardFollowcardlog->where(['id' => $arr['rec_id']])->value('top_mid');
            }

            $sinfo = $Momerchant->where('id', $top_mid)->value('wx_open_id');
            $WxOpen = new WxOpen();
            $sappid = $WxOpen->where('id', $sinfo)->value('authorizer_appid');
            $logopenid = $CardFollowcardlog->where(['id' => $arr['rec_id']])->value('openid');
            $openid = Session::get($sappid . '_openid');
            //判断领卡人是否正确]
            if ($logopenid == $openid) {
                $CardGivecardLog = new CardGivecardLog();
                $cardlist = $CardGivecardLog->where(['top_mid' => $top_mid, 'give_rec_id' => $arr['rec_id'], 'put_type' => 'follow_card'])->select();
                $card = [];
                foreach ($cardlist as $k => $v) {
                    $outer_str = 'giveRecId_' . $v['id'];
                    $isgetput = $this->isgetputsume($v['zs_card_id'], $outer_str, $openid, $v['put_sume']);
                    if ($v['put_sume'] > $v['get_sume'] && $isgetput == 0) {
                        for ($x = 0; $x < $v['put_sume']; $x++) {
                            $options = $this->options($v['zs_card_id']);
                            $arrs['card_id'] = $v['zs_card_id'];
                            $arrs['openid'] = $openid;
                            $arrs['outer_str'] = 'giveRecId_' . $v['id'];
                            $card[] = $this->putlist($arrs);
                        }
                    }
                }
                $this->assign('cardlist', $cardlist);
                if (isset($options)) {
                    $weObj = new Wxobjopen($options);
                    $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                    $jssdk = $weObj->getJsSign($url);
                    $this->assign('card', json_encode($card));
                    $this->assign('jssdk', $jssdk);
                    return $this->fetch('getcardspay');
                } else {
                    return $this->fetch('getoff');
                }
            } else {
                var_dump('您没有可领取卡券');
            }
        } catch (\Exception $e) {
            echo "系统繁忙，请稍后再试！！！";
        }
    }

    //点击菜单或回复送券
    public function getclickmsgcards()
    {
        try {
            $arr = request()->param();
            $this->_init();
            $CardClickReplyPutlog = new CardClickReplyPutlog();
            $Momerchant = new Momerchant();
            $CardMermber = new CardMember();
            //没有card_id则从rec_id中查询
            if (isset($arr['card_id'])) {
                $top_mid = $CardMermber->where('card_id', $arr['card_id'])->value('top_mid');
            } else {
                $top_mid = $CardClickReplyPutlog->where(['id' => $arr['rec_id']])->value('top_mid');
            }

            $sinfo = $Momerchant->where('id', $top_mid)->value('wx_open_id');
            $WxOpen = new WxOpen();
            $sappid = $WxOpen->where('id', $sinfo)->value('authorizer_appid');
            $logopenid = $CardClickReplyPutlog->where(['id' => $arr['rec_id']])->value('openid');
            $openid = Session::get($sappid . '_openid');
            //判断领卡人是否正确]
            if ($logopenid == $openid) {
                $CardGivecardLog = new CardGivecardLog();
                $cardlist = $CardGivecardLog->where(['top_mid' => $top_mid, 'give_rec_id' => $arr['rec_id'], 'put_type' => ['in', 'replymsg_card,click_card']])->select();
                $card = [];
                foreach ($cardlist as $k => $v) {
                    $outer_str = 'giveRecId_' . $v['id'];
                    $isgetput = $this->isgetputsume($v['zs_card_id'], $outer_str, $openid, $v['put_sume']);
                    if ($v['put_sume'] > $v['get_sume'] && $isgetput == 0) {
                        for ($x = 0; $x < $v['put_sume']; $x++) {
                            $options = $this->options($v['zs_card_id']);
                            $arrs['card_id'] = $v['zs_card_id'];
                            $arrs['openid'] = $openid;
                            $arrs['outer_str'] = 'giveRecId_' . $v['put_type'] . $v['id'];
                            $card[] = $this->putlist($arrs);
                        }
                    }
                }
                $this->assign('cardlist', $cardlist);
                if (isset($options)) {
                    $weObj = new Wxobjopen($options);
                    $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                    $jssdk = $weObj->getJsSign($url);
                    $this->assign('card', json_encode($card));
                    $this->assign('jssdk', $jssdk);
                    return $this->fetch('getcardspay');
                } else {
                    return $this->fetch('getoff');
                }
            } else {
                var_dump('您没有可领取卡券');
            }
        } catch (\Exception $e) {
            echo "系统繁忙，请稍后再试！！！";
        }
    }

    //分享送券
    public function getsharecards()
    {
//        try {
            $arr = request()->param();
            $this->_init();
            $CardShareLog = new CardShareLog();
            $Momerchant = new Momerchant();
            $CardMermber = new CardMember();
            //没有card_id则从rec_id中查询
            if (isset($arr['card_id'])) {
                $top_mid = $CardMermber->where('card_id', $arr['card_id'])->value('top_mid');
            } else {
                $top_mid = $CardShareLog->where(['id' => $arr['rec_id']])->value('top_mid');
            }

            $sinfo = $Momerchant->where('id', $top_mid)->value('wx_open_id');
            $WxOpen = new WxOpen();
            $sappid = $WxOpen->where('id', $sinfo)->value('authorizer_appid');
            $logopenid = $CardShareLog->where(['id' => $arr['rec_id']])->value('openid');
            $openid = Session::get($sappid . '_openid');
            //判断领卡人是否正确]
            if ($logopenid == $openid) {
                $CardGivecardLog = new CardGivecardLog();
                $cardlist = $CardGivecardLog->where(['top_mid' => $top_mid, 'give_rec_id' => $arr['rec_id'], 'put_type' => 'share_card'])->select();
                $card = [];
                foreach ($cardlist as $k => $v) {
                    $outer_str = 'giveRecId_' . $v['id'];
                    $isgetput = $this->isgetputsume($v['zs_card_id'], $outer_str, $openid, $v['put_sume']);
                    if ($v['put_sume'] > $v['get_sume'] && $isgetput == 0) {
                        for ($x = 0; $x < $v['put_sume']; $x++) {
                            $options = $this->options($v['zs_card_id']);
                            $arrs['card_id'] = $v['zs_card_id'];
                            $arrs['openid'] = $openid;
                            $arrs['outer_str'] = 'giveRecId_' . $v['id'];
                            $card[] = $this->putlist($arrs);
                        }
                    }
                }
//                $this->assign('cardlist', $cardlist);

                if (isset($options)) {
                    $weObj = new Wxobjopen($options);
                    $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                    $jssdk = $weObj->getJsSign($url);
                    $this->assign('card', json_encode($card));

                    $this->assign('jssdk', $jssdk);
                    return $this->fetch();
                } else {
                    return $this->fetch('getoff');
                }
            } else {
                var_dump('您没有可领取卡券');
            }
//        } catch (\Exception $e) {
//            echo "系统繁忙，请稍后再试！！！";
//        }
    }


    //等级送券
    public function getrankcards()
    {
//        try {
        $arr = request()->param();
        $this->_init();
        $CardRankUserLog = new CardRankUserLog();
        $Momerchant = new Momerchant();
        $CardMermber = new CardMember();
        //没有card_id则从rec_id中查询
        if (isset($arr['card_id'])) {
            $top_mid = $CardMermber->where('card_id', $arr['card_id'])->value('top_mid');
        } else {
            $top_mid = $CardRankUserLog->where(['id' => $arr['rec_id']])->value('top_mid');
        }

        $sinfo = $Momerchant->where('id', $top_mid)->value('wx_open_id');
        $WxOpen = new WxOpen();
        $sappid = $WxOpen->where('id', $sinfo)->value('authorizer_appid');
        $logopenid = $CardRankUserLog->where(['id' => $arr['rec_id']])->value('openid');
        $openid = Session::get($sappid . '_openid');
        //判断领卡人是否正确]
        if ($logopenid == $openid) {
            $CardGivecardLog = new CardGivecardLog();
            $cardlist = $CardGivecardLog->where(['top_mid' => $top_mid, 'give_rec_id' => $arr['rec_id'], 'put_type' => 'rank_card'])->select();
            $card = [];
            foreach ($cardlist as $k => $v) {
                $outer_str = 'giveRecId_' . $v['id'];
                $isgetput = $this->isgetputsume($v['zs_card_id'], $outer_str, $openid, $v['put_sume']);
                if ($v['put_sume'] > $v['get_sume'] && $isgetput == 0) {
                    for ($x = 0; $x < $v['put_sume']; $x++) {
                        $options = $this->options($v['zs_card_id']);
                        $arrs['card_id'] = $v['zs_card_id'];
                        $arrs['openid'] = $openid;
                        $arrs['outer_str'] = 'giveRecId_' . $v['id'];
                        $card[] = $this->putlist($arrs);
                    }
                }
            }
//                $this->assign('cardlist', $cardlist);

            if (isset($options)) {
                $weObj = new Wxobjopen($options);
                $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                $jssdk = $weObj->getJsSign($url);
                $this->assign('card', json_encode($card));

                $this->assign('jssdk', $jssdk);
                return $this->fetch();
            } else {
                return $this->fetch('getoff');
            }
        } else {
            var_dump('您没有可领取卡券');
        }
//        } catch (\Exception $e) {
//            echo "系统繁忙，请稍后再试！！！";
//        }
    }

    //等级送券
    public function getpaymentcards()
    {
//        try {
        $arr = request()->param();
        $this->_init();
        $PaymentCardPutLog = new PaymentCardPutLog();
        $Momerchant = new Momerchant();
        $CardMermber = new CardMember();
        //没有card_id则从rec_id中查询
        if (isset($arr['card_id'])) {
            $top_mid = $CardMermber->where('card_id', $arr['card_id'])->value('top_mid');
        } else {
            $Merchant = new Merchant();
            $top_mid = $Merchant->where(['id' => $arr['mid']])->value('top_mid');
        }

        $sinfo = $Momerchant->where('id', $top_mid)->value('wx_open_id');
        $WxOpen = new WxOpen();
        $sappid = $WxOpen->where('id', $sinfo)->value('authorizer_appid');
        $logopenid = $PaymentCardPutLog->where(['id' => $arr['rec_id']])->value('openid');
        $openid = Session::get($sappid . '_openid');
        //判断领卡人是否正确]
        if ($logopenid == $openid) {
            $CardGivecardLog = new CardGivecardLog();
            $cardlist = $CardGivecardLog->where(['top_mid' => $top_mid, 'give_rec_id' => $arr['rec_id'], 'put_type' => 'payment_card'])->select();
            $card = [];
            foreach ($cardlist as $k => $v) {
                $outer_str = 'giveRecId_' . $v['id'];
                $isgetput = $this->isgetputsume($v['zs_card_id'], $outer_str, $openid, $v['put_sume']);
                if ($v['put_sume'] > $v['get_sume'] && $isgetput == 0) {
                    for ($x = 0; $x < $v['put_sume']; $x++) {
                        $options = $this->options($v['zs_card_id']);
                        $arrs['card_id'] = $v['zs_card_id'];
                        $arrs['openid'] = $openid;
                        $arrs['outer_str'] = 'giveRecId_' . $v['id'];
                        $card[] = $this->putlist($arrs);
                    }
                }
            }
                $this->assign('cardlist', $cardlist);

            if (isset($options)) {
                $weObj = new Wxobjopen($options);
                $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                $jssdk = $weObj->getJsSign($url);
                $this->assign('card', json_encode($card));

                $this->assign('jssdk', $jssdk);
                return $this->fetch();
            } else {
                return $this->fetch('getoff');
            }
        } else {
            var_dump('您没有可领取卡券');
        }
//        } catch (\Exception $e) {
//            echo "系统繁忙，请稍后再试！！！";
//        }
    }

    //领取免费卡券
    public function getfreecards()
    {
        try {
            $arr = request()->param();
            $this->_init();
            if ($arr['fid']) {
                $CardFreecard = new CardFreecard();
                $Momerchant = new Momerchant();
                $freecard = $CardFreecard->where(['id' => $arr['fid']])->find();
                $sinfo = $Momerchant->where('id', $freecard['top_mid'])->value('wx_open_id');
                $WxOpen = new WxOpen();
                $sappid = $WxOpen->where('id', $sinfo)->value('authorizer_appid');
                $openid = Session::get($sappid . '_openid');
                $cardlist = json_decode($freecard['cardlist'], true);
                $isput = getfreesum($openid, $arr['fid']);
                $freecard['openid'] = $openid;
                if ($isput == 0) {
                    $card = [];
                    foreach ($cardlist as $k => $v) {
                        $options = $this->options($v['zs_card_id']);
                        $arrs['card_id'] = $v['zs_card_id'];
                        $arrs['openid'] = $openid;
                        $arrs['outer_str'] = 'freePutId_' . $arr['fid'];
                        $card[] = $this->putlist($arrs);
                    }
                    if (isset($options)) {
                        $weObj = new Wxobjopen($options);
                        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                        $jssdk = $weObj->getJsSign($url);
                        $this->assign('info', $freecard);
                        $this->assign('card', json_encode($card));
                        $this->assign('jssdk', $jssdk);
                        return $this->fetch();
                    } else {
                        return $this->fetch('getfreeoff');
                    }
                }
            }
        } catch (\Exception $e) {
            echo "系统繁忙，请稍后再试！！！";
        }
    }

    //领取跟随推荐卡券
    public function getbizcard(Request $request)
    {
        try {
            $this->_init();
            $param = $request->param();
            $Momerchant = new Momerchant();
            $CardBizPut = new CardBizPut();
            $top_mid = $CardBizPut->where(['id' => $param['give_id']])->value('top_mid');
            $sinfo = $Momerchant->where('id', $top_mid)->value('wx_open_id');
            $WxOpen = new WxOpen();
            $sappid = $WxOpen->where('id', $sinfo)->value('authorizer_appid');
            $openid = Session::get($sappid . '_openid');
            $CardGivecardLog = new CardGivecardLog();
            $map['top_mid'] = $top_mid;
            $map['card_id'] = $param['card_id'];
            $map['openid'] = $openid;
            $map['put_type'] = 'bizbonus_card';
            $cardlist = $CardGivecardLog->where($map)->field('id,zs_card_id,put_sume,get_sume')->select();
            $cardlist = collection($cardlist)->toArray();
            $card = [];
            $cards['cardlist'] = $cardlist;
            $cards['openid'] = $openid;
            $WnObj = new WnObj($cards);
            $arrs = $WnObj->isgetputsume_biz();
            $options = $this->options($param['card_id']);
            $this->assign('cardlist', $cardlist);
            if (!empty($arrs)) {
                foreach ($arrs as $k => $v) {
                    for ($x = 0; $x < $v['put_sume']; $x++) {
                        $card[] = $this->putlist($v);
                    }
                }
                $weObj = new Wxobjopen($options);
                $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                $jssdk = $weObj->getJsSign($url);
                $this->assign('card', json_encode($card));
                $this->assign('jssdk', $jssdk);

                return $this->fetch('getcardspay');
            } else {
                return $this->fetch('getoff');
            }
        } catch (\Exception $e) {
            echo '系统繁忙，请稍后再试！！！';
            echo $e->getMessage();
        }
    }

    //待领取的卡券
    public function getcardslist()
    {
        try {
            $arr = request()->param();
            $this->_init();
            $appid = $this->getappid($arr['card_id']);
            $map['openid'] = Session::get($appid . '_openid');
            $map['card_id'] = $arr['card_id'];
            $map['have'] = 1;
            $map['card_type'] = 'MEMBER_CARD';
            $CardUserGet = new CardUserGet();
            $user = $CardUserGet->where($map)->field('card_id,code,top_mid,openid,nickname,mid')->find();
            if ($user) {
                $user['get_time'] = $user['create_time'];
                $this->checkfirecards($user);
                $this->assign('card', $arr);
                $this->assign('user', $user);
                return $this->fetch();
            } else {
                return $this->fetch('off');
            }
        } catch (\Exception $e) {
            echo "系统繁忙，请稍后再试！！！";
        }
    }

    //待领取的卡券
    public function getcardslistsr()
    {
        $arr = request()->param();

        $CardGivecardLog = new CardGivecardLog();
        $cardlist = $CardGivecardLog->where(['card_id' => $arr['card_id'], 'code' => $arr['code']])->order('create_time desc')->paginate(5);
        $cardcount = $CardGivecardLog->where(['card_id' => $arr['card_id'], 'code' => $arr['code']])->count('id');
        $page_num = ceil($cardcount / 5);
        if ($cardlist) {
            if ($page_num > (int)$arr['page'] || $page_num == (int)$arr['page']) {
                $CardGel = new CardGeneral();
                $cardlists = [];
                $i = 0;
                foreach ($cardlist as $k => $v) {
                    $cards = filegetcard($v['zs_card_id'], $v['openid']);
                    if ($v['put_sume'] > $v['get_sume'] && $cards['result'] == 1) {
                        $cardlists[$i] = $v;
                        $cardlists[$i]['card_title'] = $cards['cards']['title'];
                        $cardlists[$i]['card_logo'] = $cards['cards']['logo_url'];
                        $cardlists[$i]['brand_name'] = $cards['cards']['brand_name'];
                        $cardlists[$i]['card_type'] = getcardtype($cards['cards']['card_type']);
                        $i = $i + 1;
                    }
                }
                if ($cardlists) {
                    $data['code'] = 0;
                    $data['message'] = 'SUCCESS';
                    $data['data']['data'] = $cardlists;
                    $data['page_num'] = $page_num;
                    $data['count'] = $cardcount;
                    $data['page'] = $arr['page'];
                } else {
                    $data['code'] = 0;
                    $data['data']['data'] = '';
                    $data['message'] = 'error';
                    $data['page_num'] = $page_num;
                    $data['count'] = $cardcount;
                    $data['page'] = $arr['page'];
                }
            } else {
                $data['code'] = 9002;
                $data['data']['data'] = '';
                $data['message'] = 'error';
                $data['page_num'] = $page_num;
                $data['count'] = $cardcount;
                $data['page'] = $arr['page'];
            }
        } else {
            $data['code'] = 9002;
            $data['data']['data'] = '';
            $data['message'] = 'error';
            $data['page_num'] = $page_num;
            $data['count'] = $cardcount;
            $data['page'] = $arr['page'];
        }
        return json($data);
    }


    //待领取的卡券
    public function getcardslists()
    {
        $arr = request()->param();
        $this->_init();
        $appid = $this->getappid($arr['card_id']);
        $map['openid'] = Session::get($appid . '_openid');
        $map['card_id'] = $arr['card_id'];
        $map['have'] = 1;
        $map['card_type'] = 'MEMBER_CARD';
        $CardUserGet = new CardUserGet();
        $user = $CardUserGet->where($map)->field('card_id,code,top_mid,openid,nickname,mid')->find();
        if ($user) {
            $user['get_time'] = $user['create_time'];
            $this->checkfirecards($user);
            $this->assign('card', $arr);
            $this->assign('user', $user);
            return $this->fetch();
        } else {
            return $this->fetch('off');
        }
    }

    public function getcardslisttest()
    {
        $arr = request()->param();
        $this->_init();
        $appid = $this->getappid($arr['card_id']);
        $map['openid'] = Session::get($appid . '_openid');
        $map['card_id'] = $arr['card_id'];
        $map['have'] = 1;
        $map['card_type'] = 'MEMBER_CARD';
        $CardUserGet = new CardUserGet();
        $user = $CardUserGet->where($map)->field('card_id,code,top_mid,openid,nickname,mid')->find();
        if ($user) {
            $user['get_time'] = $user['create_time'];
            $this->checkfirecards($user);
            $this->assign('card', $arr);
            $this->assign('user', $user);
            return $this->fetch();
        } else {
            return $this->fetch('off');
        }
    }

    //Ajax打开领取
    /*
     * $arr['card_id']
     */
    public function getaddcard()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            $CardGivecardLog = new CardGivecardLog();
            $log = $CardGivecardLog->where(['id' => $arr['givelogid']])->find();
            if ($log['get_sume'] < $log['put_sume']) {
                $url = $arr['url'];
                $options = $this->options($arr['card_id']);
                //发放
                $arrs['card_id'] = $arr['card_id'];
                $arrs['openid'] = Session::get($options['authorizer_appid'] . '_openid');
                $arrs['outer_str'] = 'giveRecId_' . $arr['givelogid'];
                $weObj = new Wxobjopen($options);
                $jssdk = $weObj->getJsSign($url);
                //输出内容
                $card['card'] = $this->put($arrs);
                $card['jssdk']['debug'] = false;
                $card['jssdk']['api_ticket'] = $jssdk['ticket'];
                $card['jssdk']['url'] = $jssdk['url'];
                $card['jssdk']['appId'] = $jssdk['appId'];
                $card['jssdk']['timestamp'] = $jssdk['timestamp'];
                $card['jssdk']['nonceStr'] = $jssdk['nonceStr'];
                $card['jssdk']['signature'] = $jssdk['signature'];
                $card['jssdk']['jsApiList'] = ['addCard'];
                return json($card);
            } else {
                $card = ['code' => 9001, 'msg' => '已经领完了'];
                return json($card);
            }
        }
    }

    public function getaddcards()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            $url = $arr['url'];
            $options = $this->options($arr['card_id']);
            //发放
            $arrs['card_id'] = $arr['card_id'];
            $arrs['openid'] = Session::get($options['authorizer_appid'] . '_openid');
            $arrs['outer_str'] = 'Cent';
            $weObj = new Wxobjopen($options);
            $jssdk = $weObj->getJsSign($url);
            //输出内容
            $card['card'] = $this->put($arrs);
            $card['jssdk']['debug'] = false;
            $card['jssdk']['api_ticket'] = $jssdk['ticket'];
            $card['jssdk']['url'] = $jssdk['url'];
            $card['jssdk']['appId'] = $jssdk['appId'];
            $card['jssdk']['timestamp'] = $jssdk['timestamp'];
            $card['jssdk']['nonceStr'] = $jssdk['nonceStr'];
            $card['jssdk']['signature'] = $jssdk['signature'];
            $card['jssdk']['jsApiList'] = ['addCard'];
            return json($card);
        } else {
            $card = ['code' => 9001, 'msg' => '已经领完了'];
            return json($card);
        }

    }

    /*新的开卡发券方法
     *
     * 2018/09/03
     *
     * */
    private function isgetputsume_biz($cardlist, $openid)
    {
        $arrs = "";
        try {
            if (!empty($cardlist)) {
                $card_id = implode(',', array_column($cardlist, 'zs_card_id'));
                $ids = array_column($cardlist, 'id');
                array_walk($ids, function (&$value) {
                    $value = "giveRecId_$value";
                });
                $outerstr = implode(',', $ids);
                foreach ($cardlist as $k => $v) {
                    $arrs[$v['zs_card_id']]['card_id'] = $v['zs_card_id'];
                    $arrs[$v['zs_card_id']]['outer_str'] = "giveRecId_" . $v['id'];
                    $arrs[$v['zs_card_id']]['put_sume'] = $v['put_sume'];
                    $arrs[$v['zs_card_id']]['openid'] = $openid;
                }
                $CardUserGet = new CardUserGet();
                $map['card_id'] = array('in', $card_id);
                $map['outerstr'] = array('in', $outerstr);
                $map['openid'] = $openid;
                $get_sume = $CardUserGet->where($map)->field('count(id) as get_sume,card_id')->group('card_id')->select();
                foreach ($get_sume as $k => $v) {
                    $val = $arrs[$v['card_id']];
                    if (isset($val)) {
                        if ($val['put_sume'] <= $v['get_sume']) {
                            unset($arrs[$v['card_id']]);
                        }
                    }
                }
            }
            return $arrs;
        } catch (\Exception $e) {

            return $arrs;
        }
    }
    //批量投放
    /*
     * $arr['openid'] / $arr['card_id']
     */
    private function putlist($arr)
    {
        $options = $this->options($arr['card_id']);
        $weObj = new Wxobjopen($options);
        $noncestr = $weObj->generateNonceStr();
        $outer_str = $arr['outer_str'];
        $res['cardId'] = $arr['card_id'];
        $res['cardExt'] = $weObj->wxAddCard($arr['openid'], $arr['card_id'], $noncestr, $outer_str);
        return $res;
    }

    //Ajax打开领取
    /*
     * $arr['card_id']
     */
    public function getaddcardshop()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            $url = $arr['url'];
            $options = $this->options($arr['card_id']);
            //发放
            $arrs['card_id'] = $arr['card_id'];
            $arrs['openid'] = Session::get($options['authorizer_appid'] . '_openid');
            $arrs['outer_str'] = 'shopExch_' . $arr['orderid'];
            $weObj = new Wxobjopen($options);
            $jssdk = $weObj->getJsSign($url);
            //输出内容
            $card['card'] = $this->put($arrs);
            $card['jssdk']['debug'] = true;
            $card['jssdk']['api_ticket'] = $jssdk['ticket'];
            $card['jssdk']['url'] = $jssdk['url'];
            $card['jssdk']['appId'] = $jssdk['appId'];
            $card['jssdk']['timestamp'] = $jssdk['timestamp'];
            $card['jssdk']['nonceStr'] = $jssdk['nonceStr'];
            $card['jssdk']['signature'] = $jssdk['signature'];
            $card['jssdk']['jsApiList'] = ['addCard'];
            return json($card);

        }
    }

    //投放卡
    /*
     * $arr['openid'] / $arr['card_id']
     */
    private function put($arr)
    {
        $options = $this->options($arr['card_id']);
        $weObj = new Wxobjopen($options);
        $noncestr = $weObj->generateNonceStr();
        $outer_str = $arr['outer_str'];
        $res['card_id'] = $arr['card_id'];
        $res['ext'] = $weObj->wxAddCard('', $arr['card_id'], $noncestr, $outer_str);
        return $res;
    }

    //分享jssdk
    /*
     * $card_id
     * 
     */
    private function getsharejssdk($arr)
    {
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $options = $this->options($arr);
        //分享
        $weObj = new Wxobjopen($options);
        $jssdk = $weObj->getJsSign($url);
        $wxJsSdk = [
            'debug' => false,
            'appId' => $jssdk['appId'],
            'timestamp' => $jssdk['timestamp'],
            'nonceStr' => $jssdk['nonceStr'],
            'signature' => $jssdk['signature'],
            'jsApiList' => [
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareQZone',
                'closeWindow',
                'hideAllNonBaseMenuItem',
            ]
        ];
        return $wxJsSdk;
    }

    public function cardgetsuccess()
    {
        return $this->fetch();
    }

    //免费
    public function cardgetsuccessfree()
    {
        $arr = request()->param();
        $CardFreecardlog = new CardFreecardlog();
        $arr['gettime'] = time();
        $CardFreecardlog->allowField(true)->save($arr);
        return $this->fetch('cardgetsuccess');
    }


}
